package com.yami.shop.user.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.*;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.hnaPay.BaseTransForm;
import com.yami.shop.bean.pay.WithdrawalDto;
import com.yami.shop.bean.vo.UserBalanceWithdrawCashConfigVO;
import com.yami.shop.common.bean.RequestKitBean;
import com.yami.shop.common.bean.SysConfig;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.*;
import com.yami.shop.config.HnaPayConfig;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.dao.EnterprisePayMapper;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.service.UserXsCardService;
import com.yami.shop.user.common.dao.UserBalanceWithdrawCashMapper;
import com.yami.shop.user.common.dto.UserBalanceWithdrawCashDto;
import com.yami.shop.user.common.dto.UserBalanceWithdrawCashSetDto;
import com.yami.shop.user.common.enums.UserBalanceWithdrawCashStateEnum;
import com.yami.shop.user.common.enums.WithdrawCash;
import com.yami.shop.user.common.model.UserBalanceLog;
import com.yami.shop.user.common.model.UserBalanceWithdrawCash;
import com.yami.shop.user.common.param.RangeTimeParam;
import com.yami.shop.user.common.param.UserBalanceWithdrawCashSaceParam;
import com.yami.shop.user.common.service.UserBalanceLogService;
import com.yami.shop.user.common.service.UserBalanceWithdrawCashService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@RequiredArgsConstructor
public class UserBalanceWithdrawCashServiceImpl extends ServiceImpl<UserBalanceWithdrawCashMapper, UserBalanceWithdrawCash> implements UserBalanceWithdrawCashService {
    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    private final UserBalanceWithdrawCashMapper userBalanceWithdrawCashMapper;

    private final SysConfigService sysConfigService;

    private final UserExtensionService userExtensionService;

    private final UserBalanceLogService userBalanceLogService;

    private final HnaPayConfig hnaPayConfig;

    private final UserXsCardService userXsCardService;

    private final RequestKitBean requestKitBean;

    private final ShopConfig shopConfig;

    /**
     * 导出excel列（中文）
     */
    private final static String[] EXPORT_COL_CN = {
            "用户名","用户手机号", "提现金额", "创建时间",  "更新时间", "审核时间", "审核状态"
    };
    /**
     * 导出excel列（英文）
     */
    private final static String[] EXPORT_COL_EN = {
            "User Name","User Mobile", "Withdrawal amount", "Creation time", "Update time", "Review time", "Audit status"
    };

    @Override
    public IPage<UserBalanceWithdrawCash> userBalanceWithdrawCashsPage(Page page, RangeTimeParam rangeTimeParam, String userMobile,String userName, UserBalanceWithdrawCash userBalanceWithdrawCash) {
        IPage<UserBalanceWithdrawCash> cashsPage = userBalanceWithdrawCashMapper.userWithdrawCashsPage(page, rangeTimeParam, userMobile,userName, userBalanceWithdrawCash);
        if (BooleanUtil.isFalse(permission)) {
            for (UserBalanceWithdrawCash record : cashsPage.getRecords()) {
                record.getUserVO().setUserMobile(PhoneUtil.hideBetween(record.getUserVO().getUserMobile()).toString());
                if (PrincipalUtil.isMobile(record.getUserVO().getNickName())) {
                    record.getUserVO().setNickName(PhoneUtil.hideBetween(record.getUserVO().getNickName()).toString());
                }
            }
        }
        return cashsPage;
    }

    @Override
    public IPage<UserBalanceWithdrawCashDto> userBalanceWithdrawCashDtoPageByUserId(Page page, String userId) {
        return userBalanceWithdrawCashMapper.userWithdrawCashDtoPageByUserId(page, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> apply(UserBalanceWithdrawCashSaceParam userBalanceWithdrawCashSaceParam, User user) {

        // 获取用户的钱包数据
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, user.getUserId()));

        // 获取用户提现设置
        UserBalanceWithdrawCashConfigVO userBalanceWithdrawCashConfigVO = sysConfigService.getSysConfigObject(Constant.BALANCE_WITHDRAW_CASH_CONFIG, UserBalanceWithdrawCashConfigVO.class);
        // 结算提现金额是否超出限制
        if (userBalanceWithdrawCashSaceParam.getAmount() > userBalanceWithdrawCashConfigVO.getAmountMax()) {
            // 提现金额大于最大提现金额
            throw new YamiShopBindException("yami.distribution.fee.than.error");
        }
        if (userBalanceWithdrawCashSaceParam.getAmount() < userBalanceWithdrawCashConfigVO.getAmountMin()) {
            // 提现金额小于最小提现金额
            throw new YamiShopBindException("yami.distribution.fee.less.error");
        }
        // 获取店铺设置的提现频率算出时间区间
        Calendar calendar = Calendar.getInstance();
        int monthDay = 30;
        if (userBalanceWithdrawCashConfigVO.getFrequency() == monthDay) {
            // 每月的第一天
            calendar.set(Calendar.DAY_OF_MONTH, 1);
        } else {
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - userBalanceWithdrawCashConfigVO.getFrequency());
        }
        // 将小时至0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        // 将分钟至0
        calendar.set(Calendar.MINUTE, 0);
        // 将秒至0
        calendar.set(Calendar.SECOND, 0);
        // 将毫秒至0
        calendar.set(Calendar.MILLISECOND, 0);
        RangeTimeParam rangeTimeParam = new RangeTimeParam(calendar.getTime(), new Date());
        // 获取用户最近的提现次数，判断是否能够提现
        if (userBalanceWithdrawCashMapper.getCountByRangeTimeAndUserId(rangeTimeParam, user.getUserId()) >= userBalanceWithdrawCashConfigVO.getNumber()) {
            // 提现次数为
            String message = I18nMessage.getMessage("yami.distribution.cash.num");
            String day = I18nMessage.getMessage("yami.day");
            String num = I18nMessage.getMessage("yami.constant.num");
            if (userBalanceWithdrawCashConfigVO.getFrequency() == monthDay) {
                String month = I18nMessage.getMessage("yami.distribution.cash.month");
                throw new YamiShopBindException(message + month + userBalanceWithdrawCashConfigVO.getNumber() + num);
            } else {
                throw new YamiShopBindException(message + userBalanceWithdrawCashConfigVO.getFrequency() + day + userBalanceWithdrawCashConfigVO.getNumber() + num);
            }

        }

        // 判断提现金额 是否大于钱包金额
        if (userExtension.getTotalBalance() < userBalanceWithdrawCashSaceParam.getAmount()) {
            // 提现失败,余额不足
            throw new YamiShopBindException("yami.distribution.balance.not.enough");
        }

        // 插入一条提现记录
        Date now = new Date();
        UserBalanceWithdrawCash userBalanceWithdrawCash = new UserBalanceWithdrawCash();
        userBalanceWithdrawCash.setWithdrawCashId(IdUtil.getSnowflakeNextId());
        userBalanceWithdrawCash.setUserId(user.getUserId());
        userBalanceWithdrawCash.setBizUserId(user.getXsUserId());
        userBalanceWithdrawCash.setCreateTime(now);
        userBalanceWithdrawCash.setWalletId(userExtension.getUserExtensionId());
        userBalanceWithdrawCash.setAmount(userBalanceWithdrawCashSaceParam.getAmount());
        userBalanceWithdrawCash.setVersion(0);
        userBalanceWithdrawCash.setUpdateTime(now);
        Map<String, Object> resMap = new HashMap<>();
        // 新生提现接口
        if (userBalanceWithdrawCashConfigVO.getWithdrawal().equals(WithdrawCash.Withdrawals_ZERO.getValue())) {
            userBalanceWithdrawCash.setType(1);
            userBalanceWithdrawCash.setMoneyFlow(2);
            userBalanceWithdrawCash.setState(UserBalanceWithdrawCashStateEnum.APPLY.getValue());
            userBalanceWithdrawCash.setBindCardAgrNo(ObjectUtil.isNotEmpty(userBalanceWithdrawCashSaceParam.getBindCardAgrNo()) ? userBalanceWithdrawCashSaceParam.getBindCardAgrNo() : null);
            // 新生提现默认每笔收取通道1元
            userBalanceWithdrawCash.setFee(userBalanceWithdrawCashConfigVO.getServiceAmount());
            // 存入提现记录
            userBalanceWithdrawCashMapper.insert(userBalanceWithdrawCash);

            WithdrawalDto withdrawalDto = new WithdrawalDto();
            withdrawalDto.setWithdrawCashId(userBalanceWithdrawCash.getWithdrawCashId().toString());
            withdrawalDto.setBusinessType(userBalanceWithdrawCashSaceParam.getBusinessType());
            withdrawalDto.setBindCardAgrNo(ObjectUtil.isNotEmpty(userBalanceWithdrawCashSaceParam.getBindCardAgrNo()) ? userBalanceWithdrawCashSaceParam.getBindCardAgrNo() : null);
            String cardNo;
            if (ObjectUtil.isNotEmpty(userBalanceWithdrawCashSaceParam.getBindCardAgrNo())) {
                UserXsCard userXsCard = userXsCardService.getOne(new LambdaQueryWrapper<UserXsCard>().eq(UserXsCard::getBindCardAgrNo, userBalanceWithdrawCashSaceParam.getBindCardAgrNo()));
                cardNo = userXsCard.getCardNo();
            } else {
                cardNo = userBalanceWithdrawCashSaceParam.getCardNo();
            }
            withdrawalDto.setCardNo(cardNo);
            withdrawalDto.setTranAmount(userBalanceWithdrawCashSaceParam.getAmount().toString());
            withdrawalDto.setXsUserId(user.getXsUserId());
            withdrawalDto.setServiceAmount(userBalanceWithdrawCashConfigVO.getServiceAmount().toString());
            String domainName = shopConfig.getDomain().getApiDomainName();
            withdrawalDto.setWithdrawalNoticeUrl(domainName + "/notice/pay/balanceWithdrawCash/" + userBalanceWithdrawCash.getWithdrawCashId().toString());
            BaseTransForm base = hnaPayConfig.getT002TransForm(withdrawalDto);
            try {
                Map<String, Object> post = hnaPayConfig.post(base);
                if (!post.get("resultCode").toString().equals("0000")) {
                    throw new YamiShopBindException("提现调用新生失败！");
                }
                // 增加钱包流水记录
                UserBalanceLog userBalanceLog = new UserBalanceLog();
                userBalanceLog.setCreateTime(now);
                userBalanceLog.setIoType(0);
                userBalanceLog.setType(11);
                userBalanceLog.setIsPayed(1);
                userBalanceLog.setPayNo(userBalanceWithdrawCash.getWithdrawCashId().toString());
                userBalanceLog.setUserId(user.getUserId());
                userBalanceLog.setChangeBalance(userBalanceWithdrawCashSaceParam.getAmount());
                userBalanceLog.setBindCardAgrNo(ObjectUtil.isNotEmpty(userBalanceWithdrawCashSaceParam.getBindCardAgrNo()) ? userBalanceWithdrawCashSaceParam.getBindCardAgrNo() : null);
                userBalanceLogService.save(userBalanceLog);
                resMap.put("appTime", DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN));
                resMap.put("withdrawCashId", userBalanceWithdrawCash.getWithdrawCashId());
                // enterprisePay(userBalanceWithdrawCash, user.getUserId(), user.getXsUserId(), EnterprisePayStatus.SUCCESS.getValue());
            } catch (Exception e) {
                throw new YamiShopBindException(e.getMessage());
            }
            // 修改钱包 扣除余额
            userExtension.setTotalBalance(Arith.sub(userExtension.getTotalBalance(), userBalanceWithdrawCashSaceParam.getAmount()));
            userExtensionService.updateBalanceByVersion(userExtension);
            // 修改提现记录状态
            UserBalanceWithdrawCash newWithdrawCash = BeanUtil.map(userBalanceWithdrawCash, UserBalanceWithdrawCash.class);
            newWithdrawCash.setState(UserBalanceWithdrawCashStateEnum.CASH_SUCCESS.getValue());
            userBalanceWithdrawCashMapper.updateById(newWithdrawCash);
        }

        // 判断人工审核后打款
        if (!userBalanceWithdrawCashConfigVO.getWithdrawal().equals(WithdrawCash.Withdrawals_ZERO.getValue())) {
            // 设置为手动提现
            userBalanceWithdrawCash.setType(0);
            userBalanceWithdrawCash.setMoneyFlow(2);
            userBalanceWithdrawCash.setBindCardAgrNo(ObjectUtil.isNotEmpty(userBalanceWithdrawCashSaceParam.getBindCardAgrNo()) ? userBalanceWithdrawCashSaceParam.getBindCardAgrNo() : null);
            // 新生提现默认每笔收取通道1元
            userBalanceWithdrawCash.setFee(userBalanceWithdrawCashConfigVO.getServiceAmount());
            userBalanceWithdrawCash.setState(UserBalanceWithdrawCashStateEnum.APPLY.getValue());
            // 存入提现记录
            userBalanceWithdrawCashMapper.insert(userBalanceWithdrawCash);
            // 修改钱包 新增冻结金额
            userExtension.setTotalBalance(Arith.sub(userExtension.getTotalBalance(), userBalanceWithdrawCashSaceParam.getAmount()));
            userExtension.setFreezeAmount(Arith.add(userExtension.getFreezeAmount(), userBalanceWithdrawCashSaceParam.getAmount()));
            userExtensionService.updateBalanceByVersion(userExtension);
            resMap.put("appTime", DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN));
            resMap.put("withdrawCashId", userBalanceWithdrawCash.getWithdrawCashId());
            // enterprisePay(userBalanceWithdrawCash, user.getUserId(), user.getXsUserId(), EnterprisePayStatus.APPLY.getValue());
        }
        // 判断人工审核后线下打款
        return resMap;
    }

    @Override
    public void auditWithdrawCash(Long withdrawCashId, UserBalanceWithdrawCash userBalanceWithdrawCash, Long userId, String openId) {
        UserBalanceWithdrawCash dbUserBalanceWithdrawCash = userBalanceWithdrawCashMapper.selectById(withdrawCashId);
        if (!dbUserBalanceWithdrawCash.getState().equals(ShopWithdrawCashStatus.WAITAUDIT.value())) {
            // 该申请已被审核
            throw new YamiShopBindException("yami.examine.already");
        }
        Date now = new Date();
        dbUserBalanceWithdrawCash.setAuditingTime(now);
        dbUserBalanceWithdrawCash.setAuditorId(userId);
        // 修改提现记录状态
        dbUserBalanceWithdrawCash.setState(userBalanceWithdrawCash.getState());

        UserExtension dbUserExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, dbUserBalanceWithdrawCash.getUserId()));
        UserExtension userExtension = BeanUtil.map(dbUserExtension, UserExtension.class);
        // 审核通过
        if (Objects.equals(userBalanceWithdrawCash.getState(), 1)) {
            WithdrawalDto withdrawalDto = new WithdrawalDto();
            withdrawalDto.setWithdrawCashId(userBalanceWithdrawCash.getWithdrawCashId().toString());
            withdrawalDto.setBusinessType("08");
            withdrawalDto.setBindCardAgrNo(userBalanceWithdrawCash.getBindCardAgrNo());
            UserXsCard userXsCard = userXsCardService.getOne(new LambdaQueryWrapper<UserXsCard>().eq(UserXsCard::getBindCardAgrNo, userBalanceWithdrawCash.getBindCardAgrNo()));
            withdrawalDto.setCardNo(userXsCard.getCardNo());
            withdrawalDto.setTranAmount(userBalanceWithdrawCash.getAmount().toString());
            withdrawalDto.setXsUserId(userXsCard.getXsUserId());
            withdrawalDto.setServiceAmount(dbUserBalanceWithdrawCash.getFee().toString());
            String domainName = shopConfig.getDomain().getApiDomainName();
            withdrawalDto.setWithdrawalNoticeUrl(domainName + "/notice/pay/balanceWithdrawCash/" + userBalanceWithdrawCash.getWithdrawCashId().toString());
            BaseTransForm base = hnaPayConfig.getT002TransForm(withdrawalDto);
            try {
                Map<String, Object> post = hnaPayConfig.post(base);
                if (!post.get("resultCode").toString().equals("0000")) {
                    throw new YamiShopBindException("提现调用新生失败！");
                }
                // 增加钱包流水记录
                UserBalanceLog userBalanceLog = new UserBalanceLog();
                userBalanceLog.setCreateTime(now);
                userBalanceLog.setIoType(0);
                userBalanceLog.setType(11);
                userBalanceLog.setIsPayed(1);
                userBalanceLog.setPayNo(userBalanceWithdrawCash.getWithdrawCashId().toString());
                userBalanceLog.setUserId(dbUserBalanceWithdrawCash.getUserId());
                userBalanceLog.setChangeBalance(dbUserBalanceWithdrawCash.getAmount());
                userBalanceLog.setBindCardAgrNo(dbUserBalanceWithdrawCash.getBindCardAgrNo());
                userBalanceLogService.save(userBalanceLog);
            } catch (Exception e) {
                throw new YamiShopBindException(e.getMessage());
            }
            //减去冻结的金额
            userExtension.setFreezeAmount(Arith.sub(dbUserExtension.getFreezeAmount(), dbUserBalanceWithdrawCash.getAmount()));
        } else if (Objects.equals(userBalanceWithdrawCash.getState(), -1)) {
            // 将冻结的金额返回到金额
            userExtension.setTotalBalance(Arith.add(dbUserExtension.getTotalBalance(), dbUserBalanceWithdrawCash.getAmount()));
            userExtension.setFreezeAmount(Arith.sub(dbUserExtension.getFreezeAmount(), dbUserBalanceWithdrawCash.getAmount()));
        } else {
            // 审核状态有误
            throw new YamiShopBindException("yami.examine.status.error");
        }

        // 乐观锁更新钱包信息
        if (!userExtensionService.updateById(userExtension)) {
            // 失败则抛异常
            // 服务器繁忙
            throw new YamiShopBindException("yami.network.busy");
        }
        userBalanceWithdrawCashMapper.updateById(dbUserBalanceWithdrawCash);
    }

    @Override
    public void auditNotice(HttpServletRequest request, Long withdrawCashId) {
        JSONObject reqParamJSON;
        try {
            reqParamJSON = requestKitBean.getReqParamJSON();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("通知解析数据为：reqParamJSON:{}" + JSONObject.toJSONString(reqParamJSON));
        String resultCode = reqParamJSON.getString("resultCode"); // 处理结果码
        String errorCode = reqParamJSON.getString("errorCode"); // 异常代码
        String errorMsg = reqParamJSON.getString("errorMsg"); // 异常描述
        if (resultCode.equals("0000")) {
            UserBalanceWithdrawCash userBalanceWithdrawCash = userBalanceWithdrawCashMapper.selectById(withdrawCashId);
            userBalanceWithdrawCash.setMerchantOrderId(reqParamJSON.getString("ncountOrderId"));
            userBalanceWithdrawCashMapper.updateById(userBalanceWithdrawCash);

            UserBalanceLog userBalanceLog = userBalanceLogService.getOne(new LambdaQueryWrapper<UserBalanceLog>().eq(UserBalanceLog::getPayNo, withdrawCashId));
            userBalanceLog.setIsPayed(1);
            userBalanceLogService.updateById(userBalanceLog);

        } else {
            System.out.println("提现失败{}，{}" + errorCode + errorMsg);
        }
    }

    @Override
    public void saveConfig(UserBalanceWithdrawCashSetDto userBalanceWithdrawCashSetDto) {
        CheckParam(userBalanceWithdrawCashSetDto);
        SysConfig sysConfig = new SysConfig();
        sysConfig.setRemark("提现配置");
        sysConfig.setParamValue(Json.toJsonString(userBalanceWithdrawCashSetDto));
        sysConfig.setParamKey(Constant.BALANCE_WITHDRAW_CASH_CONFIG);
        sysConfigService.saveOrUpdateSysConfigByKey(sysConfig);
    }

    private void CheckParam(UserBalanceWithdrawCashSetDto userBalanceWithdrawCashSetDto) {
        Double least = userBalanceWithdrawCashSetDto.getAmountMin();
        Double max = userBalanceWithdrawCashSetDto.getAmountMax();
        Integer frequency = userBalanceWithdrawCashSetDto.getFrequency();
        Integer number = userBalanceWithdrawCashSetDto.getNumber();
        if(Objects.isNull(least)||least<1){
            throw new YamiShopBindException("最低金额设置错误");
        }
        if(Objects.nonNull(max)&&max<least){
            throw new YamiShopBindException("最大金额设置错误");
        }
        if(Objects.isNull(frequency)||(!frequency.equals(WithdrawCashEnum.WEEKEND.value())&&!frequency.equals(WithdrawCashEnum.MONTH.value())&&!frequency.equals(WithdrawCashEnum.YEAR.value()))){
            throw new YamiShopBindException("提现频率设置错误");
        }
        if(Objects.isNull(number)||number<1){
            throw new YamiShopBindException("提现次数设置错误");
        }
    }

    @Override
    public UserBalanceWithdrawCashConfigVO getConfig() {
        UserBalanceWithdrawCashConfigVO userBalanceWithdrawCashConfigVO = sysConfigService.getSysConfigObject(Constant.BALANCE_WITHDRAW_CASH_CONFIG,UserBalanceWithdrawCashConfigVO.class);
        if(Objects.isNull(userBalanceWithdrawCashConfigVO)){
            userBalanceWithdrawCashConfigVO = new UserBalanceWithdrawCashConfigVO();
            userBalanceWithdrawCashConfigVO.setAmountMin(100D);
            userBalanceWithdrawCashConfigVO.setFrequency(1);
            userBalanceWithdrawCashConfigVO.setNumber(1);
            userBalanceWithdrawCashConfigVO.setWithdrawal(0);
            userBalanceWithdrawCashConfigVO.setServiceAmount(1D);
        }
        return userBalanceWithdrawCashConfigVO;
    }

    @Override
    public void exportShopWithdrawCash(UserBalanceWithdrawCash userBalanceWithdrawCash, HttpServletResponse response) {
        List<UserBalanceWithdrawCash> userWithdrawCashList = userBalanceWithdrawCashMapper.listExportByParam(userBalanceWithdrawCash);
        if (CollUtil.isEmpty(userWithdrawCashList)) {
            return;
        }
        ExcelWriter writer = ExcelUtil.getBigWriter();
        final List<String> exportCol = Arrays.asList(Objects.equals(I18nMessage.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang()) ? EXPORT_COL_CN : EXPORT_COL_EN);
        // 最大列数量
        int maxColNum = exportCol.size();

        Sheet sheet = writer.getSheet();
        //设置列宽
        this.setColumnWidth(sheet);
        // 标题
        writer.merge(maxColNum - 1, Objects.equals(I18nMessage.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang()) ? "用户提现信息整理" : "User withdrawal information collation");
        // 列名
        writer.writeRow(exportCol);
        int rowIndex = 2;
        for(UserBalanceWithdrawCash userWithdrawCash : userWithdrawCashList){
            int col = -1;
            // 用户名称
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, userWithdrawCash.getUserVO().getNickName());
            // 用户手机号
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, userWithdrawCash.getUserVO().getUserMobile());
            // 提现金额
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, userWithdrawCash.getAmount());
            // 创建时间
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, userWithdrawCash.getCreateTime());
            // 更新时间
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, userWithdrawCash.getUpdateTime());
            // 审核时间
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, userWithdrawCash.getAuditingTime());
            // 审核状态
            UserWithdrawCashStatus userWithdrawCashStatus = UserWithdrawCashStatus.instance(userWithdrawCash.getState());
            PoiExcelUtil.mergeIfNeed(writer, rowIndex, rowIndex, ++col, col, Objects.isNull(userWithdrawCashStatus) ? "" : userWithdrawCashStatus.text());

            ++rowIndex;
        }
        PoiExcelUtil.writeExcel(response, writer);
    }
    private void setColumnWidth(Sheet sheet) {
        // 用户名称
        sheet.setColumnWidth(0, 20 * 256);
        // 用户手机号
        sheet.setColumnWidth(1, 20 * 256);
        // 提现金额
        sheet.setColumnWidth(2, 20 * 256);
        // 创建时间
        sheet.setColumnWidth(3, 20 * 256);
        // 更新时间
        sheet.setColumnWidth(4, 20 * 256);
        // 审核时间
        sheet.setColumnWidth(5, 20 * 256);
        // 审核状态
        sheet.setColumnWidth(6, 20 * 256);

    }

    @Override
    public Integer getCountByRangeTimeAndUserId(RangeTimeParam rangeTimeParam, String userId) {
        return userBalanceWithdrawCashMapper.getCountByRangeTimeAndUserId(rangeTimeParam, userId);
    }

    @Override
    public Double getUserTotalWithdrawCash(Long walletId) {
        return userBalanceWithdrawCashMapper.getUserTotalWithdrawCash(walletId);
    }
}
